<template>
  <div class="knowledge-categories">
    <div class="page-header">
      <h1 class="page-title">知识分类管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增分类
        </el-button>
      </div>
    </div>

    <!-- 分类列表 -->
    <el-card>
      <el-table
        :data="categoryList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="250" />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="scope">
            <el-icon v-if="scope.row.icon" size="20">
              <component :is="getIconComponent(scope.row.icon)" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="isActive" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="articleCount" label="文章数" width="80" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editCategory(scope.row)"
              >编辑</el-button
            >
            <el-button size="small" @click="toggleStatus(scope.row)">
              {{ scope.row.isActive ? "禁用" : "启用" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteCategory(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            placeholder="请输入分类描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="图标">
          <el-select
            v-model="categoryForm.icon"
            placeholder="选择图标"
            clearable
          >
            <el-option
              v-for="icon in availableIcons"
              :key="icon.value"
              :label="icon.label"
              :value="icon.value"
            >
              <div class="icon-option">
                <el-icon size="16">
                  <component :is="getIconComponent(icon.value)" />
                </el-icon>
                <span>{{ icon.label }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="categoryForm.sortOrder"
            :min="0"
            :max="999"
            placeholder="排序值，越小越靠前"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="categoryForm.isActive">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitCategoryForm"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import {
  Document,
  VideoPlay,
  Question,
  FirstAidKit,
  Heart,
  Stethoscope,
  Ambulance,
  Hospital,
  User,
  Bell,
  Setting,
} from "@element-plus/icons-vue";

const categoryList = ref([]);
const loading = ref(false);
const showCreateDialog = ref(false);
const editingCategory = ref(null);
const submitLoading = ref(false);
const categoryFormRef = ref();

const categoryForm = reactive({
  name: "",
  description: "",
  icon: "",
  sortOrder: 0,
  isActive: true,
});

const categoryRules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "分类名称长度在2到100个字符",
      trigger: "blur",
    },
  ],
};

const availableIcons = [
  { value: "Document", label: "文档" },
  { value: "VideoPlay", label: "视频" },
  { value: "Question", label: "问题" },
  { value: "FirstAidKit", label: "急救箱" },
  { value: "Heart", label: "心脏" },
  { value: "Stethoscope", label: "听诊器" },
  { value: "Ambulance", label: "救护车" },
  { value: "Hospital", label: "医院" },
  { value: "User", label: "用户" },
  { value: "Bell", label: "铃铛" },
  { value: "Setting", label: "设置" },
];

const iconComponents = {
  Document,
  VideoPlay,
  Question,
  FirstAidKit,
  Heart,
  Stethoscope,
  Ambulance,
  Hospital,
  User,
  Bell,
  Setting,
};

const dialogTitle = computed(() => {
  return editingCategory.value ? "编辑分类" : "新增分类";
});

// 模拟数据
const mockCategories = [
  {
    id: 1,
    name: "急救基础知识",
    description: "基本的急救知识和技能",
    icon: "FirstAidKit",
    sortOrder: 1,
    isActive: true,
    articleCount: 25,
    createdAt: "2025-01-01 10:00:00",
  },
  {
    id: 2,
    name: "心肺复苏术",
    description: "CPR心肺复苏术相关知识",
    icon: "Heart",
    sortOrder: 2,
    isActive: true,
    articleCount: 18,
    createdAt: "2025-01-01 10:00:00",
  },
  {
    id: 3,
    name: "创伤处理",
    description: "各种创伤的处理方法",
    icon: "Ambulance",
    sortOrder: 3,
    isActive: true,
    articleCount: 32,
    createdAt: "2025-01-01 10:00:00",
  },
  {
    id: 4,
    name: "医疗急救",
    description: "医疗急救相关知识",
    icon: "Hospital",
    sortOrder: 4,
    isActive: true,
    articleCount: 15,
    createdAt: "2025-01-01 10:00:00",
  },
  {
    id: 5,
    name: "应急预案",
    description: "各种紧急情况的应对预案",
    icon: "Bell",
    sortOrder: 5,
    isActive: true,
    articleCount: 12,
    createdAt: "2025-01-01 10:00:00",
  },
];

const getIconComponent = (iconName: string) => {
  return iconComponents[iconName as keyof typeof iconComponents] || Document;
};

const loadCategories = async () => {
  loading.value = true;
  try {
    // TODO: 调用API获取分类列表
    await new Promise((resolve) => setTimeout(resolve, 500));
    categoryList.value = mockCategories;
  } catch (error) {
    console.error("加载分类列表失败:", error);
    ElMessage.error("加载分类列表失败");
  } finally {
    loading.value = false;
  }
};

const editCategory = (category: any) => {
  editingCategory.value = category;
  Object.assign(categoryForm, {
    name: category.name,
    description: category.description,
    icon: category.icon,
    sortOrder: category.sortOrder,
    isActive: category.isActive,
  });
  showCreateDialog.value = true;
};

const toggleStatus = async (category: any) => {
  try {
    const newStatus = !category.isActive;
    // TODO: 调用API更新分类状态
    console.log("更新分类状态:", category.id, newStatus);
    category.isActive = newStatus;
    ElMessage.success("操作成功");
  } catch (error) {
    console.error("更新分类状态失败:", error);
    ElMessage.error("操作失败");
  }
};

const deleteCategory = async (category: any) => {
  if (category.articleCount > 0) {
    ElMessage.warning("该分类下还有文章，不能删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // TODO: 调用API删除分类
    console.log("删除分类:", category.id);
    const index = categoryList.value.findIndex((c) => c.id === category.id);
    if (index > -1) {
      categoryList.value.splice(index, 1);
    }
    ElMessage.success("删除成功");
  } catch (error) {
    console.log("取消删除");
  }
};

const submitCategoryForm = async () => {
  if (!categoryFormRef.value) return;

  await categoryFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (editingCategory.value) {
          // 编辑分类
          console.log("编辑分类:", categoryForm);
          // TODO: 调用API更新分类
        } else {
          // 新增分类
          console.log("新增分类:", categoryForm);
          // TODO: 调用API创建分类
        }

        showCreateDialog.value = false;
        resetCategoryForm();
        loadCategories();
        ElMessage.success("操作成功");
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetCategoryForm = () => {
  editingCategory.value = null;
  Object.assign(categoryForm, {
    name: "",
    description: "",
    icon: "",
    sortOrder: 0,
    isActive: true,
  });
  categoryFormRef.value?.clearValidate();
};

// 初始化加载
onMounted(() => {
  loadCategories();
});

// 监听对话框关闭重置表单
watch(showCreateDialog, (newVal) => {
  if (!newVal) {
    resetCategoryForm();
  }
});
</script>

<style scoped>
.knowledge-categories {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.icon-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
